/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.firebird.base.orm;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.Assert;

/**
 * @author qiuxj
 * @date 2009-11-14
 */
public class SqlUtils {

	  private static final Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", 2);

	  public static String removeSelect(String sql)
	  {
	    Assert.hasText(sql);
	    int beginPos = sql.toLowerCase().indexOf(" from ");
	    Assert.isTrue(beginPos != -1, "sql:" + sql + " must has a keyword 'from'");
	    return sql.substring(beginPos);
	  }

	  public static String limitSelect(String sql, int limit)
	  {
	    Assert.hasText(sql);
	    String nsql = sql.toLowerCase();
	    if ((limit > 0) && (nsql.indexOf(" union ") == -1) && (nsql.indexOf(" first ") == -1)) {
	      int beginPos = nsql.indexOf("select");
	      Assert.isTrue(beginPos != -1, "sql:" + sql + " must has a keyword 'select'");

	      return "select first " + limit + sql.substring(beginPos + 6);
	    }
	    return sql;
	  }

	  public static String removeOrders(String sql)
	  {
	    Assert.hasText(sql);
	    Matcher m = p.matcher(sql);
	    StringBuffer sb = new StringBuffer();
	    while (m.find()) {
	      m.appendReplacement(sb, "");
	    }
	    m.appendTail(sb);
	    return sb.toString();
	  }

	  public static void main(String[] args) {
	    String a = "AddA";
	    String b = a.toLowerCase();
	    System.out.println(a);
	    System.out.println(b);
	    System.out.println(limitSelect("select * from TAB", 2));
	  }

	
}
